package common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

/**
 * 
 * @author Administrator
 *
 */
public class HttpClient {

	// 创建上下文
	private static HttpClientContext context = HttpClientContext.create();
	// 浏览器
	private static CloseableHttpClient httpClient = null;

	// 初始化
	static {
		httpClient = HttpClients.createDefault();
		CookieStore cookieStore = new BasicCookieStore();
		context.setCookieStore(cookieStore);
		System.out.println("初始化完成...");
	}

	public static CloseableHttpResponse httpGet(String url, String referer) throws Exception {
		HttpGet get = new HttpGet(url);
		return execute(get, referer);
	}
	public static CloseableHttpResponse httpPost(String url, Map<String, String> map, String chartSet)
			throws Exception {
		HttpPost post = new HttpPost(url);
		List<NameValuePair> parameters = new ArrayList<>();
		for (Entry<String, String> ele : map.entrySet()) {
			parameters.add(new BasicNameValuePair(ele.getKey(), ele.getValue()));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, chartSet);
		// 设置参数
		post.setEntity(entity);
		return execute(post, url);
	}

	private static CloseableHttpResponse execute(HttpUriRequest request, String referer) throws Exception {
		request.setHeader("Accept-Language", "zh;q=0.8");
		request.setHeader("Accept-Encoding", "gzip, deflate, sdch");
		request.setHeader("Connection", "keep-alive");
		request.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
		request.setHeader("Referer", referer);
		CloseableHttpResponse Response = httpClient.execute(request, context);
		return Response;
	}
	public void stopClient() throws IOException {
		httpClient.close();
	}

}
